package com.snail.auth.service;

import com.snail.auth.form.LoginBody;
import com.snail.common.core.constant.*;
import com.snail.common.core.domain.R;
import com.snail.common.core.enums.UserStatus;
import com.snail.common.core.exception.ServiceException;
import com.snail.common.core.text.Convert;
import com.snail.common.core.utils.StringUtils;
import com.snail.common.core.utils.ip.IpUtils;
import com.snail.common.redis.service.RedisService;
import com.snail.common.security.utils.SecurityUtils;
import com.snail.system.api.RemoteUserService;
import com.snail.system.api.domain.SysRole;
import com.snail.system.api.domain.SysUser;
import com.snail.system.api.dto.SysTenantDto;
import com.snail.system.api.dto.SysUserDto;
import com.snail.system.api.model.LoginUser;
import com.snail.thirdparty.api.RemoteThirdPartyService;
import com.snail.thirdparty.api.dto.SmsDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 登录校验方法
 *
 * @author snail
 */
@Component
public class SysLoginService {
    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysRecordLogService recordLogService;

    @Autowired
    private RedisService redisService;
    @Autowired
    private RemoteThirdPartyService remoteThirdPartyService;

    /**
     * 登录
     */
    public LoginUser login(LoginBody form) {
        //用户名
        String username = form.getUsername();
        //密码
        String password = form.getPassword();
        //手机号
        String phone = form.getPhone();
        SysUserDto userDto = null;
        //账号密码登录
        if (TokenConstants.ACCOUNT_LOGIN.equals(form.getType())) {
            // 用户名或密码为空 错误
            if (StringUtils.isAnyBlank(username, password)) {
                recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户/密码必须填写");
                throw new ServiceException("用户/密码必须填写");
            }
            // 用户名或密码为空 错误
            if (StringUtils.isAnyBlank(username, password)) {
                recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户/密码必须填写");
                throw new ServiceException("用户/密码必须填写");
            }
            // 密码如果不在指定范围内 错误
            if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                    || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
                recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户密码不在指定范围");
                throw new ServiceException("用户密码不在指定范围");
            }
            // 用户名不在指定范围内 错误
            if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                    || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
                recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户名不在指定范围");
                throw new ServiceException("用户名不在指定范围");
            }
            // IP黑名单校验
            String blackStr = Convert.toStr(redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST));
            if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
                recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "很遗憾，访问IP已被列入系统黑名单");
                throw new ServiceException("很遗憾，访问IP已被列入系统黑名单");
            }
            // 查询用户信息
            R<SysUserDto> userResult = remoteUserService.getUserByUserName(username, SecurityConstants.INNER);
            if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData())) {
                recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在");
                throw new ServiceException("登录用户：" + username + " 不存在");
            }
            if (R.FAIL == userResult.getCode()) {
                throw new ServiceException(userResult.getMsg());
            }
            userDto = userResult.getData();
        }
        // 手机号登录
        else if (TokenConstants.PHONE_LOGIN.equals(form.getType())) {
            String key = StringUtils.format(CacheConstants.SMS_CODE_KEY, phone);
            // key 是自己才可以释放，不是就不能释放别人的锁
            String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1] then " +
                    "    return redis.call(\"del\",KEYS[1]) " +
                    " else " +
                    "    return 0 " +
                    "end";
            RedisScript<Boolean> redisScript = RedisScript.of(script, Boolean.class);
            List<String> keys = Collections.singletonList(key);
            // 执行脚本的时候传递的 value 就是对应的值
            Boolean executeScript = redisService.executeScript(redisScript, keys, form.getSmsCode());
            if (!executeScript) {
                recordLogService.recordLogininfor(phone, Constants.LOGIN_FAIL, "验证码错误");
                throw new ServiceException("验证码错误");
            }
            // 查询用户信息
            R<SysUserDto> userResult = remoteUserService.getUserByPhone(phone, SecurityConstants.INNER);
            if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData())) {
                recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在");
                throw new ServiceException("登录用户：" + username + " 不存在");
            }
            if (R.FAIL == userResult.getCode()) {
                throw new ServiceException(userResult.getMsg());
            }
            userDto = userResult.getData();
        }
        if (StringUtils.isNull(userDto)) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在");
            throw new ServiceException("登录用户：" + username + " 不存在");
        }
        if (UserStatus.DELETED.getCode().equals(userDto.getDelFlag())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(userDto.getStatus())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new ServiceException("对不起，您的账号：" + username + " 已停用");
        }
        passwordService.validate(userDto, password);
        recordLogService.recordLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功");

        LoginUser loginUser = new LoginUser();
        //用户信息
        loginUser.setSysUser(userDto);
        //部门
        loginUser.setSysDept(userDto.getDept());
        //权限
        loginUser.setPermissions(userDto.getPermissions());
        //角色
        loginUser.setSysRoles(userDto.getRoles());
        Set<String> roles = userDto.getRoles().stream().map(SysRole::getRoleKey).collect(Collectors.toSet());
        loginUser.setRoles(roles);
        //部门权限
        loginUser.setDeptPermission(userDto.getDeptPermission());
        return loginUser;
    }

    public void logout(String loginName) {
        recordLogService.recordLogininfor(loginName, Constants.LOGOUT, "退出成功");
    }

    /**
     * 注册
     */
    public void register(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password)) {
            throw new ServiceException("用户/密码必须填写");
        }
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            throw new ServiceException("账户长度必须在2到20个字符之间");
        }
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            throw new ServiceException("密码长度必须在5到20个字符之间");
        }

        // 注册用户信息
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        sysUser.setNickName(username);
        sysUser.setPassword(SecurityUtils.encryptPassword(password));
        R<?> registerResult = remoteUserService.registerUserInfo(sysUser, SecurityConstants.INNER);

        if (R.FAIL == registerResult.getCode()) {
            throw new ServiceException(registerResult.getMsg());
        }
        recordLogService.recordLogininfor(username, Constants.REGISTER, "注册成功");
    }

    /**
     * 获取多租户
     *
     * @return 多租户
     */
    public List<SysTenantDto> getTenant() {
        return redisService.getCacheObject(CacheConstants.TENANT_KEY);
    }

    public boolean sendSmsCode(String phone) {
        //手机号校验
        if (StringUtils.isEmpty(phone)) {
            throw new ServiceException("手机号不能为空!");
        }
        //判断用户信息是否存在
        R<SysUserDto> userResult = remoteUserService.getUserByPhone(phone, SecurityConstants.INNER);
        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData())) {
            throw new ServiceException("手机号不存在");
        }
        //缓存key
        String key = StringUtils.format(CacheConstants.SMS_CODE_KEY, phone);
        //判断释放发送过验证码
        if (redisService.getCacheObject(key) != null) {
            throw new ServiceException("请勿重复发送,请稍后再试!");
        }
        Random random = new Random();
        //验证码
        String code = String.valueOf(random.nextInt(900000) + 100000);
        redisService.setCacheObject(key, code, 300L, TimeUnit.SECONDS);

        SmsDto smsDto = new SmsDto();
        smsDto.setPhone(phone);
        smsDto.setCode(code);
        R<Boolean> r = remoteThirdPartyService.sendSmsCode(smsDto, SecurityConstants.INNER);
        if (!r.isOk()) {
            throw new ServiceException(r.getMsg());
        }
        return true;
    }
}
